<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card>
            <!-- 添加按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="RolesDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

            <!-- 角色列表 -->
            <el-table :data="rolesList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightId(scope.row, item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级三级权限 -->
                            <el-col :span="19">
                                <!-- 二级权限 -->
                                <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, index2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightId(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3, index3) in item2.children" :key="item3.id" closable @close="removeRightId(scope.row, item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top"  :enterable="false">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditUser(scope.row.id)">编辑</el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top"  :enterable="false">
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="remoUserId(scope.row.id)">删除</el-button>
                        </el-tooltip>
                        
                            <el-button size="mini" type="warning" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                     
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加用户弹出框 -->
            <el-dialog title="添加用户" :visible.sync="RolesDialogVisible" width="50%">
                <el-form :model="addRolesList" :rules="addUserListRules" ref="addUserListRef" label-width="90px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRolesList.roleName"></el-input>
                    </el-form-item>  
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRolesList.roleDesc"></el-input>
                    </el-form-item> 
                </el-form>    
                <span slot="footer" class="dialog-footer">
                    <el-button @click="RolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUserList">确 定</el-button>
                </span>
            </el-dialog>
            
            <!-- 编辑用户窗口 -->
            <el-dialog title="编辑用户" :visible.sync="EditVisible" width="50%">
                <el-form :model="editRolesList" :rules="editUserListRules" ref="editUserListRef" label-width="90px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editRolesList.roleName" disabled></el-input>
                    </el-form-item>  
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editRolesList.roleDesc"></el-input>
                    </el-form-item> 
                </el-form>    
                <span slot="footer" class="dialog-footer">
                    <el-button @click="EditVisible = false">取 消</el-button>
                    <el-button type="primary" @click="rolesEditInfo">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
            <!-- 分配权限窗口 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="alloRigths">确 定</el-button>
            </span>
        </el-dialog>    
    </div>
</template>

<script>
export default {
    data() {
        return {
            rolesList: [],
            RolesDialogVisible: false,
            addRolesList: {
                roleName: '',
                roleDesc: ''
            },
            addUserListRules: {
                roleName: [
                    { required: true, message: '请输入账号名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入职位', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    // { pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文' }
                ]
            },
            EditVisible: false,
            editRolesList: {},
            editUserListRules: {
                roleDesc: [
                    { required: true, message: '请输入职位', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    // { pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文' }
                ]
            },
            // 权限分配窗口
            setRightDialogVisible: false,
            rightList: [],
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            // 权限管理默认的三级权限获取数组。
            defKeys: [],
            // 点击权限分配时保存的id  数据提交时使用
            roleId: ''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
       async getRolesList() {
           const { data:res } = await this.$http.get('roles')
           if(res.meta.status !== 200) {
               return this.$message.error('获取角色列表失败')
           }
           this.rolesList = res.data
        },
        // 添加用户
        addUserList() {
            this.$refs.addUserListRef.validate(async valid => {
                if(!valid) return
                const { data: res } = await this.$http.post('roles', this.addRolesList)
                if(res.meta.status !== 201) {
                    return this.$message.error('添加用户失败')
                }
                this.$message.success('添加用户成功')
                // 点击确定关闭对话框
                this.RolesDialogVisible = false
                // 成功添加用户刷新数据列表
                this.getRolesList()
                // 将对话框添加的内容重置为空
                this.$refs.addUserListRef.resetFields()
            })
        },
        // 编辑用户先获取要编辑用户的信息
        async showEditUser(id) {
            const { data: res } = await this.$http.get('roles/' + id)
            if(res.meta.status !== 200) {
                return this.$message.error('获取角色信息失败')
            }
            this.editRolesList = res.data
            this.EditVisible = true
            // console.log(this.editRolesList)
        },
        // 获取到信息后进行编辑确定提交修改后的数据然后重新调用数据列表
        rolesEditInfo() {
            this.$refs.editUserListRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('roles/' + this.editRolesList.roleId, {
                    roleName: this.editRolesList.roleName,
                    roleDesc: this.editRolesList.roleDesc
                })
                if(res.meta.status !== 200) {
                    return this.$message.error('修改失败')
                }
                this.$message.success('修改成功')
                this.EditVisible = false
                this.getRolesList()
                // this.$refs.editUserListRef.resetFields()
            })
        },
        async remoUserId(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户点击确定删除，返回字符串confirm
            // 如果用户点击取消删除，返回字符串cancel
            if(confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete('roles/' + id)
            if(res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
            this.getRolesList()
        },
        async removeRightId(role, rightId) {
            // $confirm返回值时 Promise 为了简化  要写async和await
            const confimRemoveId = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户点击确定删除，返回字符串confirm
            // 如果用户点击取消删除，返回字符串cancel
            if(confimRemoveId !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            // this.getRolesList()
            role.children = res.data
        },
        async showSetRightDialog(role) {
            this.roleId = role.id
            const { data: res } = await this.$http.get('rights/tree')
            if(res.meta.status !== 200) {
                return this.$message.error('获取权限数据失败')
            }
            this.rightList = res.data
            // 点击权限管理按钮时触发自定义递归函数
            this.getLeafKeys(role, this.defKeys)
            this.setRightDialogVisible = true
            // console.log(this.defKeys)
        },
        // 自定义递归函数，为了获取权限管理默认数据。
        getLeafKeys(node, arr) {
            // 三级权限值是没有children的，如果没有说明是三级权限，然后将值添加到数组
            if(!node.children) {
                return arr.push(node.id)
            }
            // 如果有children 说明不是三级权限，需要循环寻找，直到找到并将三级权限添加到数组为止。
            node.children.forEach(item => this.getLeafKeys(item, arr))
        },
        // 监听权限管理窗口关闭事件，重置勾选的数据
        setRightDialogClosed() {
            this.defKeys = []
        },
        async alloRigths() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            // console.log(keys)
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: idStr
            })
            if(res.meta.status !== 200) {
                return this.$message.error('分配失败')
            }
            this.$message.success('分配成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
    .el-button {
        margin-bottom: 20px;
    }
    .el-tag {
        margin: 7px;
    }
    .bdtop {
        border-top: 1px solid #eee;
    }
    .bdbottom {
        border-bottom: 1px solid #eee;
    }
    .vcenter {
    display: flex;
    align-items: center;
}
</style>